import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup} from "@angular/forms";
import {BarnProduct} from "../entity/barn-product";
import {ProductService} from "../service/product.service";
import {concatMap} from "rxjs/operators";
import {SystemInfoService} from "../../../basic-data/system-info/service/system-info.service";
import {RoleInfoService} from "../../../basic-data/role/service/role-info.service";
import {BarnSystemInfo} from "../../../basic-data/system-info/entity/barn-system-info";
import {RoleUser} from "../../../basic-data/role/entity/role-user";

@Component({
  selector: 'app-product-info',
  templateUrl: './product-info.component.html',
  styleUrls: ['./product-info.component.less']
})
export class ProductInfoComponent implements OnInit  {

  validateForm = new FormGroup({
    productName: new FormControl(),
    enable: new FormControl(''),
    userId: new FormControl('')
  })

  users: RoleUser[] = []

  products: BarnProduct[] = []
  current = 1;
  pageSize = 20;
  total = 1000;
  pageSizes = [this.pageSize, 50, 100]
  loading = false


  constructor(private productService: ProductService, private systemInfoService: SystemInfoService,
              private roleInfoService: RoleInfoService) {
  }


  ngOnInit(): void {
    this.search();
    this.getProductManagers()
  }

  search() {
    this.loading = true
    const param = this.validateForm.getRawValue()
    this.productService.query(param, this.current, this.pageSize)
      .subscribe(value => {
        this.products = value.data
        this.current = value.current || 1
        this.total = value.count || 1
        this.loading = false
      }, () => this.loading = false)

  }

  getProductManagers() {
    this.systemInfoService.getById(BarnSystemInfo.PRODUCT_MANAGER_ROLE_ID).pipe(
      concatMap(v => {
        return this.roleInfoService.getUsers({roleId: v.variableValue,isInclude:'1'} as RoleUser)
      })
    ).subscribe(value => {
      this.users = value.data
    })
  }

  resetForm() {
    this.validateForm.reset({enable:'',userId:''})
  }
}
